//
//  MyController.swift
//  baihuiju
//
//  Created by 赵家彬 on 2018/5/23.
//  Copyright © 2018年 赵家彬. All rights reserved.
//

import UIKit
import MJRefresh
import RxSwift

class MyController: CBBaseViewController {

    @IBOutlet weak var vwScroll: UIScrollView!
    
    @IBOutlet weak var btnAvatar: UIButton!
    
    @IBOutlet weak var lblName: UILabel!
    
    @IBOutlet weak var lblMobile: UILabel!
    
    @IBOutlet weak var lblAvlMoney: UILabel!
    
    @IBOutlet weak var lblCYFR: UILabel!
    
    var updateUserInfo:Variable<Bool> = Variable(true)
    var userModel:Variable<UserModel?> = Variable(MainTools.shared.userModel)
    var vipInfoModel:GolfVipInfoModel = GolfVipInfoModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        vwScroll.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(initData))
        
        updateUserInfo.asObservable()
            .subscribe(onNext: { [weak self] _ in self?.initData() })
            .disposed(by: disposeBag)
        
        NotificationCenter.default.rx
            .notification(NSNotification.Name.init(rawValue: "Flush_User_Info"))
            .subscribe(onNext: { [weak self] _ in self?.initData() })
            .disposed(by: disposeBag)
        
        lblName.addTapGesture(target: self, selector: #selector(pushToLogin))
        lblMobile.addTapGesture(target: self, selector: #selector(pushToLogin))
        lblAvlMoney.addTapGesture(target: self, selector: #selector(pushToLogin))
        lblCYFR.addTapGesture(target: self, selector: #selector(pushToLogin))
        
    }
    
    @objc func pushToLogin() {
        guard let _ = MainTools.shared.userModel else {
            presentLogin()
            return
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: true)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: true)
    }
    
    var isQueryGolfVipStatus = false
    @objc func initData() {
        if let userModel = MainTools.shared.userModel {
            NetworkTool.requestData(url: ActionURL.USER_CENTER, param: ["uid":userModel.uid])
                .map { (json) -> Bool in
                    MainTools.shared.userModel = UserModel.mj_object(withKeyValues: json["rows"].dictionaryObject)
                    return true
                }
                .catchErrorJustReturn(false)
                .observeOn(MainScheduler.instance)
                .subscribe(onNext:{ [unowned self] isSuccess in
                    self.vwScroll.mj_header.endRefreshing()
                    self.userModel.value = MainTools.shared.userModel
                    self.flushView()
                }).disposed(by: disposeBag)
            
            isQueryGolfVipStatus = true
            NetworkTool.requestData(url: ActionURL.GET_GOLF_VIP_INFO, param: ["uid":MainTools.shared.userModel?.uid ?? ""])
                .map { (json) -> GolfVipInfoModel? in
                    return GolfVipInfoModel.mj_object(withKeyValues: json["rows"].dictionaryValue["data"]?.dictionaryObject)
                }.catchErrorJustReturn(nil)
                .observeOn(MainScheduler.instance)
                .subscribe(onNext:{ [unowned self] opModel in
                    if let tmpModel = opModel {
                        self.vipInfoModel = tmpModel
                    }
                    self.isQueryGolfVipStatus = false
                }).disposed(by: disposeBag)
            
        } else {
            vwScroll.mj_header.endRefreshing()
        }
        flushView()
    }
    
    func flushView() {
        if let userModel = MainTools.shared.userModel {
            btnAvatar.setBackgroundImage(UIImage(named: (userModel.img.isEmpty || userModel.img == "0") ? "null_avtar" : userModel.img), for: .normal)
            lblName.text = "您好 " + userModel.realname
            lblMobile.text = userModel.mobile
            lblAvlMoney.text = userModel.balance
            lblCYFR.text = userModel.accrual
        } else {
            btnAvatar.setBackgroundImage(UIImage(named: "null_avtar"), for: .normal)
            lblName.text = "登录/注册"
            lblMobile.text = "--"
            lblAvlMoney.text = "--"
            lblCYFR.text = "--"
        }
    }
    
}

//跳转
extension MyController {
    
    //弹出登录窗口
    func presentLogin() {
        self.navigationController?.tabBarController?.modalTransitionStyle = UIModalTransitionStyle.crossDissolve
        self.navigationController?.tabBarController?.present((UIStoryboard(name: "LoginAndRegister", bundle: nil).instantiateInitialViewController() as? UINavigationController) ?? UINavigationController(), animated: true, completion:nil)
    }
    
    //跳转到设置
    @IBAction func pushToSet(_ sender: Any) {
        guard let _ = MainTools.shared.userModel else {
            presentLogin()
            return
        }
        let setVc = UserSetController(nibName: "UserSetController", bundle: nil)
        setVc.hidesBottomBarWhenPushed = true
        setVc.userModel = userModel
        setVc.updateUserInfo = updateUserInfo
        self.navigationController?.pushViewController(setVc, animated: true)
    }

    //跳转到项目管理
    @IBAction func pushToProjectManage(_ sender: UITapGestureRecognizer) {
        guard let userModel = MainTools.shared.userModel else {
            presentLogin()
            return
        }
        let myOrderVc = MyOrderController()
        myOrderVc.hidesBottomBarWhenPushed = true
        myOrderVc.userModel = userModel
        self.navigationController?.pushViewController(myOrderVc, animated: true)
    }
    
    //跳转到我要充值
    @IBAction func pushToCharge(_ sender: UITapGestureRecognizer) {
        guard let _ = MainTools.shared.userModel else {
            presentLogin()
            return
        }
        let chargeVc:ChargeController = MainTools.initSbVc(sbName: "My", AnyClass: ChargeController.self)
        chargeVc.hidesBottomBarWhenPushed = true
        chargeVc.userModel = userModel
        chargeVc.updateUserInfo = updateUserInfo
        self.navigationController?.pushViewController(chargeVc, animated: true)
    }
    
    //跳转难道我要提现
    @IBAction func pushToWithdraw(_ sender: UITapGestureRecognizer) {
        guard let _ = MainTools.shared.userModel else {
            presentLogin()
            return
        }
        let withdrawVc:WithdrawController = MainTools.initSbVc(sbName: "My", AnyClass: WithdrawController.self)
        withdrawVc.hidesBottomBarWhenPushed = true
        withdrawVc.userModel = userModel
        self.navigationController?.pushViewController(withdrawVc, animated: true)
        
    }
    
    //跳转到资金记录
    @IBAction func pushToMoneyRecord(_ sender: UITapGestureRecognizer) {
        guard let _ = MainTools.shared.userModel else {
            presentLogin()
            return
        }
        let fundRecordVc:FundRecordController = FundRecordController()
        fundRecordVc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(fundRecordVc, animated: true)
    }
    
    //打开头像
    @IBAction func pushAvatar(_ sender: UIButton) {
        guard let _ = MainTools.shared.userModel else {
            presentLogin()
            return
        }
    }
    
    //跳转我的高尔夫
    @IBAction func pushToMyGolf(_ sender: UITapGestureRecognizer) {
        guard let _ = MainTools.shared.userModel else {
            presentLogin()
            return
        }
        
        if isQueryGolfVipStatus {
            return
        }
        
        if vipInfoModel.name.isEmpty && vipInfoModel.price.isEmpty && vipInfoModel.address.isEmpty
            && vipInfoModel.start_time.isEmpty {
            //普通会员
            let normalVc = MainTools.initSbVc(sbName: "My", AnyClass: MyGolfNormalController.self)
            normalVc.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(normalVc, animated: true)
        } else {
            //VIP
            let vipVc = MainTools.initSbVc(sbName: "My", AnyClass: MyGolfVipController.self)
            vipVc.vipInfoModel = vipInfoModel
            vipVc.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(vipVc, animated: true)
        }

    }
    
    
}
